/*
 * @Author: your name
 * @Date: 2021-08-17 14:57:54
 * @LastEditTime: 2021-10-03 09:58:05
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue_study\src\network\request.js
 */
import axios from "axios";
import { Dialog, Toast } from "vant";
import router from "../router";


export function request(config) {
    const instance = axios.create({
        baseURL: 'https://api.shop.eduwork.cn/',
        timeout: 5000
    })

    //请求拦截
    instance.interceptors.request.use(config => {
        //如果有接口需要认证后访问，在此处统一设置
        const token = window.localStorage.getItem('token')

        if (token) {
            config.headers.Authorization = 'Bearer ' + token
        }
        //直接放行
        return config
    }, err => {

    })

    //响应拦截
    instance.interceptors.response.use(res => {
        return res.data ? res.data : res;
    }, err => {
        //如果有需要认证才可以访问的接口，统一去登录授权
        if (err.response.status == '401') {
            Toast.fail('请先登录')
            router.push({
                path: '/login'
            })
        }
        //显示错误信息
        Dialog.alert({
            message: err.response.data.errors[Object.keys(err.response.data.errors)[0]][0]
        }).then(() => {
            // on close
        });
    })
    return instance(config)
}